package cn.shop.dys.adapter;

import android.content.Context;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;

import java.util.ArrayList;
import java.util.List;

import cn.shop.dys.R;
import cn.shop.dys.bean.CartBean;
import cn.shop.dys.bean.CartProInDB;
import cn.shop.dys.bean.ProductProperty;
import cn.shop.dys.constant.SPConstant;
import cn.shop.dys.dao.CartDao;
import cn.shop.dys.util.SPUtil;
import cn.shop.dys.widget.SnappingStepper;
import cn.shop.lib_common.ComUtils;
import cn.shop.lib_common.ComViewHolder;

/**
 * Created by Administrator on 2016/4/15.
 */
public class CartAdapter extends BaseAdapter implements View.OnClickListener,
        SnappingStepper.SnappingStepperValueChangeListener,
        CompoundButton.OnCheckedChangeListener {

    private Context mContext;
    private List<CartBean> mList;
    private List<CartBean> selectedGoods;

    public CartAdapter(Context context, List<CartBean> list) {
        super();
        this.mContext = context;
        this.mList = list;
        selectedGoods = new ArrayList<>();
    }

    public List<CartBean> getList() {
        return mList;
    }

    @Override
    public int getCount() {
        return mList == null ? 0 : mList.size();
    }

    @Override
    public Object getItem(int position) {
        return mList.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        final ComViewHolder holder = ComViewHolder.newInstance
                (mContext, convertView, R.layout.item_cart);
        final CartBean cart = mList.get(position);

        holder.getTv(R.id.pro_name).setText(cart.proName);
        ImageView pro_image = holder.getView(R.id.pro_image, ImageView.class);

        Glide.with(mContext).load(cart.proImg).centerCrop().crossFade().into(pro_image);

        holder.getTv(R.id.pro_shopPrice).setText(ComUtils.getShowPrice(cart.shopPrice));
        TextView pro_property = holder.getView(R.id.pro_property, TextView.class);
        List<ProductProperty> productPropertys = cart.productPropertys;
        String text = propropertyListToText(productPropertys);
        if (!TextUtils.isEmpty(text)) {
            pro_property.setText(text);
        }
        SnappingStepper stepper = holder.getView(R.id.stepper, SnappingStepper.class);

        TextView btnCartDelete = holder.getView(R.id.btn_delete, TextView.class);
        if (cart.buttonIsVisible) {
            btnCartDelete.setVisibility(View.VISIBLE);
        } else {
            btnCartDelete.setVisibility(View.INVISIBLE);
        }
        btnCartDelete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                deleteAnimation(holder.getView(), cart);
            }
        });
        stepper.setTag(position);
        stepper.setValue(cart.proCount);
        stepper.setMaxValue(cart.number);
        stepper.setOnValueChangeListener(this);

        CheckBox itemCb = holder.getView(R.id.item_cb, CheckBox.class);
        itemCb.setChecked(cart.isSelected);
        itemCb.setTag(position);
        itemCb.setOnClickListener(this);
        itemCb.setOnCheckedChangeListener(this);
        mCallback.onColorChange(colors[i%12]);
        holder.getView().setBackgroundResource(colors[i++%12]);

        return holder.getView();
    }

    int i = 0;
    private int[] colors = {R.color.material_red_100, R.color.material_pink_100, R.color.material_purple_100, R.color.material_indigo_100,
            R.color.material_blue_100, R.color.material_cyan_100, R.color.material_teal_100, R.color.material_green_100, R.color.material_lime_100,
            R.color.material_yellow_100, R.color.material_amber_100, R.color.material_orange_100};

    private String propropertyListToText(List<ProductProperty> productPropertys) {
        String propropertyText = new String();
        if (productPropertys != null && productPropertys.size() > 0) {
            for (ProductProperty productProperty : productPropertys) {
                propropertyText += productProperty.getK() + ":" + productProperty.getV() + "  ";
            }

        }
        return propropertyText;
    }

    private void deleteAnimation(View itemView, final CartBean cart) {


        TranslateAnimation translateAnimation = new TranslateAnimation(Animation.RELATIVE_TO_PARENT, 0, Animation.RELATIVE_TO_PARENT, 1.0f, 0, 0, 0, 0);
        translateAnimation.setDuration(500);
        translateAnimation.setInterpolator(new AccelerateInterpolator());

        translateAnimation.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {

            }

            @Override
            public void onAnimationEnd(Animation animation) {
                mList.remove(cart);
//                if (cart.isSelected) {
//                    selectedGoods.remove(cart);
//                    mCallback.onProductCheckedChanged(selectedGoods);

//                }
                notifyDataSetChanged();
                if (mCartIsEmptyListener != null && mList.isEmpty()) {
                    mCartIsEmptyListener.onViewGone();
                } else if (mCartIsEmptyListener != null) {
                    mCartIsEmptyListener.onViewVisible();
                }

                // 删除数据库
                String userId = SPUtil.getString(mContext, SPConstant.USER_INFO_USER_ID);

                    CartDao.remove(userId, cart.proId);


                setAccount();
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });
        itemView.startAnimation(translateAnimation);

    }

//    private CartProInDB cartToCartProInDB(CartBean cart) {
//        String userId = SPUtil.getString(mContext, SPConstant.USER_INFO_USER_ID);
//        if (!TextUtils.isEmpty(userId)){
//            //// TODO: 2016/4/22 userID
//            userId="20428";
//
//        }else {
//            userId="20428";
//        }
//        int productId = cart.proId;
//
//        int productNum = cart.proCount;
//        String proproperty = propropertyListToString(cart.productPropertys);
//        CartProInDB cartProInDB = new CartProInDB(userId,productId,productNum,proproperty);
//        return cartProInDB;
//
//
//    }
//    private String propropertyListToString(List<ProductProperty> productPropertys) {
//        String propropertyText = new String();
//        if (productPropertys != null && productPropertys.size() > 0) {
//            for (ProductProperty productProperty : productPropertys) {
//                propropertyText += productProperty.getId() + ",";
//            }
//            propropertyText = propropertyText.substring(0, propropertyText.length() - 1);
//
//        }
//        return propropertyText;
//    }

    public void selectAll(boolean selectAll) {
        if (mList != null) {
            for (CartBean cartBean : mList) {
                cartBean.isSelected = selectAll;
            }
            if (selectAll) {

                selectedGoods.clear();
                selectedGoods.addAll(mList);
            } else {
                selectedGoods.clear();
            }
            notifyDataSetChanged();
            if (mCartIsEmptyListener != null && mList.isEmpty()) {
                mCartIsEmptyListener.onViewGone();
            } else if (mCartIsEmptyListener != null) {
                mCartIsEmptyListener.onViewVisible();
            }

            setAccount();
//            mCallback.onProductCheckedChanged(selectedGoods);
        }
    }

    @Override
    public void onValueChange(View view, int value) {
        int position = (int) view.getTag();
        CartBean cartBean = mList.get(position);
        cartBean.proCount = value;

        upDBData(cartBean);
        setAccount();
//        mCallback.onProductCheckedChanged(selectedGoods);
    }

    private void upDBData(CartBean cartBean) {
        String userId = SPUtil.getString(mContext, SPConstant.USER_INFO_USER_ID);
        //// TODO: 2016/4/21 获取用户id


        if (userId != null) {
            List<ProductProperty> productPropertys = cartBean.productPropertys;
            String proProperty = new String();
            if (productPropertys != null && productPropertys.size() != 0) {

                for (ProductProperty productProperty : productPropertys) {
                    proProperty += productProperty.getId() + ",";
                }
                //Log.d("test",proProperty);
                proProperty = proProperty.substring(0, proProperty.length() - 1);
            }
            CartProInDB cartProInDB = new CartProInDB(userId, cartBean.proId, cartBean.proCount, proProperty);
            //Log.d("test",cartProInDB.toString());
            CartDao.remove(userId, cartBean.proId);
            CartDao.add(cartProInDB);

        }
    }

    private float mAccount;

    public float getAccount() {
        return mAccount;
    }

    public void setAccount() {
        mAccount = 0;
        if (mList != null) {
            for (CartBean cartBean : mList) {
                if (cartBean.isSelected) {
                    mAccount += cartBean.shopPrice * cartBean.proCount;
                }
            }
        }
        mCallback.onAccountChange();
    }


    public interface Callback {
        void onColorChange(int color);
        void onChecked();

        void onCancel();

        void onAccountChange();

//        void onProductCheckedChanged(List<CartBean> selectedGoods);
    }

    private Callback mCallback;

    public void setCallback(Callback callback) {
        this.mCallback = callback;
    }

    @Override
    public void onClick(View v) {
        // Log.d("CartAdapter", "onClick");
        int position = (int) v.getTag();
        boolean checked = ((CheckBox) v).isChecked();
        mList.get(position).isSelected = checked;
        Log.d("test", checked + "");
        setAccount();

        if (checked) {
//            selectedGoods.add(mList.get(position));
//            //Log.d("test", selectedGoods.toString());
//            mCallback.onProductCheckedChanged(selectedGoods);
//            for (CartBean cartBean : mList) {
//                if (!cartBean.isSelected) {
//                    return;
//                }
//
//            }
            mCallback.onChecked();


        } else {
            mCallback.onCancel();
//            selectedGoods.remove(mList.get(position));
        }
//        mCallback.onProductCheckedChanged(selectedGoods);
    }

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
//        setAccount();
//        mCallback.onAccountChange();
    }

    public interface CartIsEmptyListener {
        void onViewGone();

        void onViewVisible();
    }

    private CartIsEmptyListener mCartIsEmptyListener;

    public void setCartIsEmptyListener(CartIsEmptyListener mCartIsEmptyListener) {
        this.mCartIsEmptyListener = mCartIsEmptyListener;
    }
}
